{% assign tiktok_pixel_id = storeConfig.tiktok_pixel_id | strtoarray %}
{% get_pixels_domain list={tiktok_pixel_id} %}
{%- assign pixels = list -%}
{% if pixels %}
<script>
    !function (w, d, t) {
    w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
      {% for pixel in pixels %}
        ttq.load('{{ pixel.facebook_pixel_id }}');
      {% endfor %}
      ttq.page();
    }(window, document, 'ttq');
    document.addEventListener("DOMContentLoaded",function(){
      ttq.identify({
        {% if pixel_user.email %}
          email: '{{pixel_user.email | string_sha256 }}',
        {% endif %}
        {% if pixel_user.phone_number %}
        phone_number:"{{ pixel_user.phone_number | pixelPhoneNumberFormat:'tiktok',pixel_user.tel_area_code }}",
        {% endif %}
        external_id: "{% if pixel_user.id %}{{ pixel_user.id | string_sha256 }}{% endif %}"
      })

      function pushPixel(name){
        ttq.track.apply(null,arguments)
      }
      window['TOP_GLOBAL_CALLBACK_LAYER'].register({
        view_content:function(){
          pushPixel("ViewContent",{
            currency: _GET_C_SETTING_('base_currency_code'),
            value:_GET_C_SETTING_('product').variant.price,
            contents:[
              {
                content_id: _GET_C_SETTING_('product').spu,
                content_name: _GET_C_SETTING_('product').variant.title,
                content_type:"product",
                quantity: 1,
                price: _GET_C_SETTING_('product').variant.price,
                currency: _GET_C_SETTING_('base_currency_code')
              }
            ]
          })
        },
        search:function(){
          pushPixel('Search',{
            currency: _GET_C_SETTING_('base_currency_code'),
            value:0,
            contents:_GET_C_SETTING_('search_products').map(item=>{
              return {
                content_id: item.spu,
                content_type: "product",
                content_name: item.title
              }
            }),
            query:'{{search.keywords | filter_string_format}}'
          })

        },
        purchase:function(){
          {%- if controller == 'order' and action == 'success' -%}
            {% capture pixels %}tiktok_pixels_{{order.id}}{% endcapture %}
            {% get_cache key={pixels} var_name=tiktok_pixels_status%}
            {% if tiktok_pixels_status ==0 %}
              pushPixel('CompletePayment', {
                content_id: _GET_C_SETTING_('cart').order_number,
                contents:_GET_C_SETTING_('cart').products.map(item=>{
                    return   {
                      content_id:  item.spu,
                      content_type: "product",
                      quantity: item.quantity,
                      price: item.price,
                     
                    }
                }),
                {%- if storeConfig.snapchat_sales_goods_amount -%}
                'value': "{{ order.current_subtotal_price| plus:order.current_coupon_price | plus:order.current_promotion_price }}",
                {%- else -%}
                'value': "{{ order.total_price }}",
                {%- endif -%}
                currency: "{{order.currency_code}}"
              },{event_id:'{{order.order_number}}'});
            {% endif %}
          {% endif %}
        },
        add_to_wishlist:function(ecdata){
          pushPixel('AddToWishlist', {
            currency: _GET_C_SETTING_('base_currency_code'),
            value:ecdata['ec_data_price'] * ecdata['ec_data_quantity'],
            contents:[
              {
                content_id: ecdata['ec_data_spu'],
                content_type: "product",
                content_name: ecdata['ec_data_name']
              }
            ]
          });
        },
        add_to_cart:function(ecdata){
          pushPixel('AddToCart', {
            currency: _GET_C_SETTING_('base_currency_code'),
            value:ecdata['ec_data_price'] * ecdata['ec_data_quantity'],
            contents:[
              {
                content_id: ecdata['ec_data_spu'],
                content_type: "product",
                content_name: ecdata['ec_data_name']
              }
            ]
          });
        },
        place_an_order:function(){
          pushPixel("PlaceAnOrder",{
            currency: _GET_C_SETTING_('base_currency_code'),
            value:_GET_C_SETTING_('cart').total_price,
            contents:_GET_C_SETTING_('cart').items.map(item=>{
                return   {
                  content_id:  item.product.spu,
                  content_type: "product",
                  quantity: item.quantity,
                  price: item.price,
                }
            })
          })
        },
        add_payment_information:function(){
          pushPixel('AddPaymentInfo', {
            currency: _GET_C_SETTING_('base_currency_code'),
            value:_GET_C_SETTING_('cart').total_price,
            contents:_GET_C_SETTING_('cart').items.map(item=>{
                return   {
                  content_id:  item.product.spu,
                  content_type: "product",
                  quantity: item.quantity,
                  price: item.price,
                }
            })
          });
        },
        begin_checkout:function(){
          pushPixel('InitiateCheckout', {
            currency: _GET_C_SETTING_('base_currency_code'),
            value:_GET_C_SETTING_('cart').total_price,
            contents:_GET_C_SETTING_('cart').items.map(item=>{
                return   {
                  content_id:  item.product.spu,
                  content_type: "product",
                  quantity: item.quantity,
                  price: item.price,
                }
            })
          });
        },
        sign_up:function(){
          pushPixel('CompleteRegistration');
        }
      })
    }) 
</script>
{% endif %}
